<?php

namespace App\Repositories\System;

use  App\Repositories\Repository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use App\Models\Logs;
use App\Repositories\User\UserRepository;

class UserActionLog extends Repository {

	protected $user;
	protected $model;
	protected $UserRepository;
	protected $order = array('create_time', 'desc');

	public function __construct(Logs $model, UserRepository $UserRepository) {
		$this->user           = Auth::user();
		$this->model          = $model;
		$this->UserRepository = $UserRepository;
	}


	/**
	 * 构造搜索条件
	 * @param $condition
	 * @return array
	 */
	public function SearchCondition($condition) {
		$SearchCondition = array();

		if ($condition['keyword_type'] && $condition['keywords']) {
			$user = $this->UserRepository->condition($condition)->all(array('id'));
			$SearchCondition['user_id'] =  array('in',array_flatten($user->toArray()));
		}

		return $SearchCondition;
	}


	/**
	 * 记录日志
	 * -------------------
	 * message 需要在语言包 resources->lang->cn->user_action 中配置好
	 * @param string $module 模块
	 * @param string $action 动作
	 * @param string $level  日志三个等级: info/warning/error
	 * @return mixed
	 */
	public function record($module, $action, $level = 'info') {
		$log = $this->model->create([
			'user_id'     => intval($this->user->id),
			'module'      => $module,
			'action'      => $action,
			'message'     => trans('user_action.' . $module . '_' . $action, ['name' => $this->user->name]),
			'level'       => $level,
			'create_time' => time(),
			'ip'          => Request::getClientIp()
		]);

		return $log;
	}

}
